import time,sched
import os
import datetime
import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from appAdminUseClassroom_new.models import ClassroomuseinfoIf, Classroombasicinfo,\
    ClassroomuseinfoWaiyu,ClassroomuseinfoJidian,ClassroomuseinfoJingguan,Building
#导入cv模块
import cv2 as cv
#导入百度智能识别人流量模块
from appFlowStatistics.baiduFlow import *
'''这个模块是空闲教室流量统计的模块
首先读取当前的系统时间，然后根据当前的系统时间去查询当前空闲的教室。
每隔五分钟从img文件夹中读取照片，返回空闲教室的人数在前端'''
'''需要改进的地方：用openCV太慢，用百度智能云错误太多'''
#该函数用来获取当前的系统时间
def getCurrentTime():

    #根据这个学期学校的校历，转换成第几教学周、星期几、第几大节的课程
    date0 = time.strptime('2022-02-21', "%Y-%m-%d") #格式转换
    date1 = time.localtime(time.time())#当前的日期
    date0 = datetime.datetime(date0[0], date0[1], date0[2])
    date1 = datetime.datetime(date1[0], date1[1], date1[2])
    # 两个变量相差的值，就是相差天数
    differ = date1 - date0
    week = differ // datetime.timedelta(days=7) + 1

    day = int(time.strftime("%w", time.localtime()))  # 星期（0 - 6），星期天为星期的开始
    if day==0:#将星期天转换成7而不是0，符合数据库中的形式
        day=7
    hour = int(time.strftime("%H", time.localtime()))  # 当前的小时
    minute = int(time.strftime("%M", time.localtime()))  # 当前的分钟

    #将时间转换成第几节课
    time_=1
    if hour==8 or (hour==9 and minute<=55):
        time_=1
    elif (hour==9 and minute>55) or (hour>=10 and hour<=12) or (hour==13 and minute<=30):
        time_=2
    elif (hour==13 and minute>30) or (hour==14) or (hour==15 and minute<=20):
        time_=3
    elif (hour==15 and minute>20) or (hour==16) or (hour==17 and minute<=10):
        time_=4
    elif (hour==17 and minute>10) or (hour==18) or (hour==19 and minute<=30):
        time_=5
    elif (hour==19 and minute>30) or (hour==20) or (hour==21 and minute<=15):
        time_=6
    return week,day,time_

def appendFreeClassroom(data,list_,time_interval):
    time_interval=0 #这里不应该写死time_interval，但是没有准备足够的照片，所以重复使用当前时段的照片。
    building_name = Building.objects.all()  # 楼栋表，用来查楼栋的名称

    i=0
    for classroom in list_:  # 遍历空闲教室列表，将需要用到的信息转换，然后封装成json的形式

        i+=1
        data_dict = {}
        data_dict["building_id"] = classroom["building_id"]
        data_dict["cid"] = classroom["cid"]
        data_dict["building_name"] = building_name[classroom["building_id"] - 1].building_name
        data_dict["classroom_name"] = Classroombasicinfo.objects\
            .values("building_id", "cid", "classroom_name")\
            .get(building_id=classroom["building_id"], cid=classroom["cid"])["classroom_name"]

        # 根据当前的楼栋、教室、刷新次数，去对应的img文件夹中调取图片，跑流量统计的代码，返回给前端
        if classroom['state'] == 1 and i<8:  # 只显示当前时间段空闲的教室
            if classroom["building_id"] == 1:  # 去逸夫楼img文件夹中提取照片
                path = f'static/img/building_If/{str(classroom["cid"]-25*(classroom["building_id"]-1))}_{str(time_interval)}.jpg'
                # data_dict["flow_num"] = get_person_num(path) #百度智能云流量统计接口
                #opencv流量统计接口
                img=cv.imread(path)
                data_dict["flow_num"] = face_detect_demo(img)
                print("当前路径：", path)
                print("流量：",data_dict["flow_num"])
            if classroom["building_id"] == 2:
                path = f'static/img/building_Jidian/{str(classroom["cid"]-25*(classroom["building_id"]-1))}_{str(time_interval)}.jpg'
                # data_dict["flow_num"] = get_person_num(path)
                img = cv.imread(path)
                data_dict["flow_num"] = face_detect_demo(img)
                print("当前路径：", path)
                print("流量：", data_dict["flow_num"])
            if classroom["building_id"] == 3:
                path = f'static/img/building_Jingguan/{str(classroom["cid"]-25*(classroom["building_id"]-1))}_{str(time_interval)}.jpg'
                # data_dict["flow_num"] = get_person_num(path)
                img = cv.imread(path)
                data_dict["flow_num"] = face_detect_demo(img)
                print("当前路径：", path)
                print("流量：", data_dict["flow_num"])
            if classroom["building_id"] == 4:
                path = f'static/img/building_Waiyu/{str(classroom["cid"]-25*(classroom["building_id"]-1))}_{str(time_interval)}.jpg'
                # data_dict["flow_num"] = get_person_num(path)
                img = cv.imread(path)
                data_dict["flow_num"] = face_detect_demo(img)
                print("当前路径：", path)
                print("流量：", data_dict["flow_num"])
            data.append(data_dict)

    return data

#定向到显示空闲教室流量的页面
def flowStatistics_index(request):
    week, day, time = getCurrentTime()  # 获取当前时间，并且转换成对应的教学周、
    week=16
    return render(request,"flow_statistics.html",{"week":week,"day":day,"time":time})

#查询数据库，返回空闲教室的信息
def flowStatistics(request):
    week, day, time = getCurrentTime()  # 获取当前时间，并且转换成对应的教学周、
    week = 16
    time_interval=request.POST.get("time_interval",{"week":week,"day":day,"time":time})
    #初次定位到首页的时候，没有reload表格，将这个值赋值为0
    if time_interval == None:
        time_interval=0
    print("打印时间间隔",time_interval)
    If_list=ClassroomuseinfoIf.objects\
        .values("use_id","building_id","cid","week","day","time","state","remark")\
        .filter(week=week,day=day,time=time)

    Jidian_list=ClassroomuseinfoJidian.objects \
        .values("use_id", "building_id", "cid", "week", "day", "time", "state", "remark") \
        .filter(week=week,day=day,time=time)

    Jingguan_list=ClassroomuseinfoJingguan.objects \
        .values("use_id", "building_id", "cid", "week", "day", "time", "state", "remark") \
        .filter(week=week,day=day,time=time)

    Waiyu_list=ClassroomuseinfoWaiyu.objects \
        .values("use_id", "building_id", "cid", "week", "day", "time", "state", "remark") \
        .filter(week=week,day=day,time=time)

    data=[]#存放传向前端的信息
    data = appendFreeClassroom(data,If_list,time_interval)
    data = appendFreeClassroom(data,Jidian_list,time_interval)
    data = appendFreeClassroom(data, Jingguan_list,time_interval)
    data = appendFreeClassroom(data, Waiyu_list,time_interval)
    return JsonResponse({
        "code": 0,
        "flag": 0,
        "data": data
    })


#检测图像
def face_detect_demo(img):
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    #加载分类器,调用opeccv自带的haar分类器，没有自己训练（自己训练还涉及到机器学习和深度学习了，目前只是简单实现）
    #这里的路径目前是绝对路径，相对路径会报错
    #face_detect = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
    face_detect = cv.CascadeClassifier('D:/pythonProject/djangoProject1/facedetect/haarcascade_frontalface_default.xml')
    face=face_detect.detectMultiScale(gray)
    for x,y,w,h in face:
        cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
    return (len(face))

